package luanvan.app.foodnote;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;

import luanvan.app.foodnote.library.AddressFromLatLng;
import luanvan.app.foodnote.library.GPSTracker;
import luanvan.app.foodnote.library.JSONParser;
import luanvan.app.foodnote.library.MyLocation;
import luanvan.app.foodnote.library.MyLocation.LocationResult;
import luanvan.app.foodnote.library.TypeFood;
import luanvan.app.foodnote.library.UserFunctions;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;


public class NewFoodActivity extends SherlockActivity implements LocationListener {

	private ProgressDialog pDialog;
	JSONParser jsonParser = new JSONParser();
	AddressFromLatLng addresFromLatLng;
	
	JSONObject placesObj = null;
	JSONArray places = null;
	
	ArrayList<String> arrayPlaces;
	
	// url to create new food
    private static String url_create_food = "http://192.168.0.129/foodnote/create_food.php";
	private static String url_get_type_foods = "http://192.168.0.129/foodnote/get_type_foods.php";
    
    /*private static String url_create_food = "http://10.0.2.2/foodnote/create_food.php";
    private static String url_get_type_foods = "http://10.0.2.2/foodnote/get_type_foods.php";*/
   
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PLACE_NAME = "TEN_DIA_DIEM";
    private static final String TAG_NAME = "TEN_MON_AN";
    private static final String TAG_ADDRESS = "DIA_CHI";
    private static final String TAG_CITY = "THANH_PHO";
    private static final String TAG_PHONE = "SO_DIEN_THOAI";
    private static final String TAG_DESCRIPTION = "MO_TA";
    private static final String TAG_LATITUDE = "LATITUDE";
    private static final String TAG_LONGITUDE = "LONGITUDE";
    private static final String TAG_UID = "uid";
    private static final String TAG_PLACES = "places";
    private static final String TAG_TYPE_FOOD_NAME_ID = "LOAI_MON_AN_id";
    
    // Type Foods
    private static final String TAG_TYPE_ID = "id";
    private static final String TAG_TYPE_FOODS = "TEN_LOAI_MON_AN";
    

    private static final int TEN_METERS = 10;
    private static final int TWO_MINUTES = 1000 * 60 * 2;
	
    private EditText inputPlaceName;
	private EditText inputName;
	private TextView inputAddress;
	private EditText inputPhonenumber;
	private EditText inputOthernotes;
	private Button btnSave;
	private Button getAddresses;
	private Spinner spnTypeFood;
	
	private double log;
	private double lat;

	LocationManager locationManager;
	
	TypeFood mSelected;
	
	// GPSTracker class
	GPSTracker gps;
	
	boolean confirm = false;
	
	String foodId = null;
	
	String address = "";
	String cities = "";
	
	private Location loc;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_LEFT_ICON);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.form_add);
		getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.plus);
		
		getSupportActionBar().setDisplayShowTitleEnabled(true);
		getSupportActionBar().setIcon(getResources().getDrawable(R.drawable.plus));
		
		inputPlaceName = (EditText) findViewById(R.id.EditPlaceName);
		inputName = (EditText) findViewById(R.id.EditName);
		inputAddress = (TextView) findViewById(R.id.EditAddr1);
		
		spnTypeFood = (Spinner) findViewById(R.id.spnLoaiMonAn);
		
		inputPhonenumber = (EditText) findViewById(R.id.EditTel);
		//inputCity = (AutoCompleteTextView) findViewById(R.id.autocomplete_cities);
		inputOthernotes = (EditText) findViewById(R.id.EditNotes);
		//inputLocation = (TextView) findViewById(R.id.location);
		btnSave = (Button) findViewById(R.id.saveFood);
		getAddresses = (Button) findViewById(R.id.getAddresses);
		
		// Find Current Location
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location location = locationManager
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		if (location != null) {
			Log.d("Location", location.toString());
			this.onLocationChanged(location);
			new GetAddresses().execute(new Location[] {location});
		}
		else {
			/*gps = new GPSTracker(getApplicationContext());
			gps.showSettingsAlert();*/
		}
		
		new GetTypeFood().execute();
		
		spnTypeFood.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View arg1,
					int pos, long id) {
				// TODO Auto-generated method stub
				 mSelected = (TypeFood) parent.getItemAtPosition(pos);
				 Log.i("Id:", mSelected.getId());
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});

		//this.getTypeFoods();
		
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				new CreateNewFood().execute();
			}
		});
		
		getAddresses.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				ShowListAddresses();
			}
		});
	}
	
    ArrayList<String> listAddresses;
	private class GetAddresses extends AsyncTask<Location, Void, String>{

		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewFoodActivity.this);
            pDialog.setTitle("Xin chờ");
            pDialog.setMessage("Đang tìm địa chỉ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		@Override
		protected String doInBackground(Location... params) {
			final Location loc = params[0];
			listAddresses = new ArrayList<String>();
			addresFromLatLng = new AddressFromLatLng(loc);
	
			
			address = addresFromLatLng.Address();
			cities = addresFromLatLng.Address4();
			listAddresses = addresFromLatLng.listAddress();
			
			return null;
		}
		
		protected void onPostExecute(String file_url) {
            // dismiss the dialog once done
            pDialog.dismiss();
            runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					inputAddress.setText(address);
				}
			});
        }
	}
	
	String presentAddress;
	private void ShowListAddresses(){
		final String[] items = new String[listAddresses.size()];
		for (int i = 0; i < listAddresses.size(); i++){
			items[i] = listAddresses.get(i);
		}
		
		AlertDialog.Builder builder = new AlertDialog.Builder(NewFoodActivity.this);
    	builder.setTitle("Địa điểm hiện tại");
    	builder.setIcon(R.drawable.mark_red);
    	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int item) {
				//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				presentAddress = items[item];
			}
		});
    	builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
    		
    		public void onClick(DialogInterface dialog, int id) {
    			//Toast.makeText(NewFoodActivity.this, "Success" + id, Toast.LENGTH_SHORT).show();
    			inputAddress.setText("");
    			inputAddress.setText(presentAddress);
    		}
	    });
    	builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int id) {
    			dialog.dismiss();
    		}
	    });
    	AlertDialog alert = builder.create();
    	alert.show();
		
	}
	class CreateNewFood extends AsyncTask<String, String, String>{
		String place = "";
		@Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(NewFoodActivity.this);
            pDialog.setTitle("Xin chờ");
            pDialog.setMessage("Đang thêm món ăn...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }
		
		@Override
		protected String doInBackground(String... args) {	
			
			String placename = inputPlaceName.getText().toString();
			String name = inputName.getText().toString();
			String address = inputAddress.getText().toString();
			String city = cities;
			String phone = inputPhonenumber.getText().toString();
			String description = inputOthernotes.getText().toString();
			String latitude = String.valueOf(lat);
			String longitude = String.valueOf(log);
			
			//Log.e("String Place Name", placename);
			
			if(!placename.isEmpty() && !name.isEmpty() && !address.isEmpty() && !city.isEmpty()){
				UserFunctions userFunction = new UserFunctions();
				String uid = userFunction.getUID(getApplicationContext());

				//Log.d("UID", uid);
			
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(TAG_PLACE_NAME, placename));
				params.add(new BasicNameValuePair(TAG_NAME, name));
				params.add(new BasicNameValuePair(TAG_ADDRESS, address));
				params.add(new BasicNameValuePair(TAG_CITY, city));
				params.add(new BasicNameValuePair(TAG_PHONE, phone));
				params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
				params.add(new BasicNameValuePair(TAG_LATITUDE, latitude));
				params.add(new BasicNameValuePair(TAG_LONGITUDE, longitude));
				params.add(new BasicNameValuePair(TAG_TYPE_FOOD_NAME_ID, mSelected.getId()));
				
				params.add(new BasicNameValuePair(TAG_UID, uid));
				//params.add(new BasicNameValuePair("confirm", String.valueOf(false)));
				
				JSONObject json = jsonParser.makeHttpRequest(url_create_food, "POST", params);
				// check log cat fro response
	            Log.e("Create Response", json.toString());
	            
	            try {
	            	int success = json.getInt(TAG_SUCCESS);
	            	
	            	if(success == 1){
	            		Intent i = new Intent(getApplicationContext(), AllFoodsActivity.class);
	            		startActivity(i);
	            		finish();
	            	} else if(success == 2) {
	                    //Log.e("Duplicate Location", "Có thể bị trùng địa điểm");
	                    //placesObj = json.getJSONObject(TAG_PLACES);
	                    places = json.getJSONArray(TAG_PLACES);
	                    arrayPlaces = new ArrayList<String>();
	                    for(int i = 0; i < places.length(); i++){
	                    	//JSONObject jsonObject = places.getJSONObject(i);
	                    	
	                    	String placeName = places.getString(i);
	                    	
	                    	arrayPlaces.add(placeName);
	                    }
	                    removeDuplicate(arrayPlaces);
	                    runOnUiThread(new Runnable() {
							
							@Override
							public void run() {
								ShowListLocationDuplicate(arrayPlaces);
							}
						});
	                }
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
			}
			
			return null;
		}
		protected void onPostExecute(String file_url) {
			
            // dismiss the dialog once done
            pDialog.dismiss();
        
        }
	}
	
	public static void removeDuplicate(ArrayList<String> arlList)
	{
	   HashSet<String> h = new HashSet<String>(arlList);
	   arlList.clear();
	   arlList.addAll(h);
	}
	String placeList = "";
	private void ShowListLocationDuplicate(ArrayList<String> places){
		
		final String[] items = new String[places.size()];
		for(int i = 0; i< places.size(); i++){
			items[i] = places.get(i);
		}
    	AlertDialog.Builder builder = new AlertDialog.Builder(NewFoodActivity.this);
    	builder.setTitle("Địa điểm đã lưu, có phải địa điểm sau?");
    	builder.setIcon(R.drawable.mark_red);
    	builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int item) {
				//Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
				placeList = items[item];
			}
		});
    	builder.setPositiveButton("Đồng Ý",new DialogInterface.OnClickListener() {
    		
    		public void onClick(DialogInterface dialog, int id) {
    			//Toast.makeText(NewFoodActivity.this, "Success" + id, Toast.LENGTH_SHORT).show();
    			inputPlaceName.setText("");
    			inputPlaceName.setText(placeList);
    			confirm = true;
    			new ConfirmSaveFood().execute(String.valueOf(confirm));
    		}
	    });
    	builder.setNegativeButton("Hủy", new DialogInterface.OnClickListener() {
    		public void onClick(DialogInterface dialog, int id) {
    			confirm = true;
    			dialog.dismiss();
    			new ConfirmSaveFood().execute(String.valueOf(confirm));
    		}
	    });
    	AlertDialog alert = builder.create();
    	alert.show();
	}
	
	private class ConfirmSaveFood extends AsyncTask<String, Void, String>{

		@Override
		protected String doInBackground(String... args) {
			String conf = args[0];
			String placename = inputPlaceName.getText().toString();
			String name = inputName.getText().toString();
			String address = inputAddress.getText().toString();
			String city = cities;
			String phone = inputPhonenumber.getText().toString();
			String description = inputOthernotes.getText().toString();
			String latitude = String.valueOf(lat);
			String longitude = String.valueOf(log);
			
			
			//Log.e("String Place Name", placename);
			
			if(!placename.isEmpty() && !name.isEmpty() && !address.isEmpty() && !city.isEmpty()){
				UserFunctions userFunction = new UserFunctions();
				String uid = userFunction.getUID(getApplicationContext());

				//Log.d("UID", uid);
			
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair(TAG_PLACE_NAME, placename));
				params.add(new BasicNameValuePair(TAG_NAME, name));
				params.add(new BasicNameValuePair(TAG_ADDRESS, address));
				params.add(new BasicNameValuePair(TAG_CITY, city));
				params.add(new BasicNameValuePair(TAG_PHONE, phone));
				params.add(new BasicNameValuePair(TAG_DESCRIPTION, description));
				params.add(new BasicNameValuePair(TAG_LATITUDE, latitude));
				params.add(new BasicNameValuePair(TAG_LONGITUDE, longitude));
				params.add(new BasicNameValuePair(TAG_TYPE_FOOD_NAME_ID, mSelected.getId()));
				
				params.add(new BasicNameValuePair(TAG_UID, uid));
				params.add(new BasicNameValuePair("confirm", conf));
				Log.d("Confirm variable", String.valueOf(confirm));
				
				JSONObject json = jsonParser.makeHttpRequest(url_create_food, "POST", params);
				// check log cat fro response
	            Log.e("Create Response", json.toString());
	            
	            try {
	            	int success = json.getInt(TAG_SUCCESS);
	            	
	            	if(success == 1){
	            		Intent i = new Intent(getApplicationContext(), AllFoodsActivity.class);
	            		startActivity(i);
	            		finish();
	            	} 
	            } catch (JSONException e) {
	                e.printStackTrace();
	            }
			}
			return null;
		}
		
	}
	@Override
	protected void onResume() {
		super.onResume();
		LocationResult locationResult = new LocationResult() {
			
			@Override
			public void gotLocation(Location location) {

				/*double lat = location.getLatitude();
				double lng = location.getLongitude();
				
				Log.d("Location", String.valueOf(lat) + ", " + String.valueOf(lng));*/
			}
		};
		MyLocation myLocation = new MyLocation();
		if(!myLocation.getLocation(this, locationResult)){
			Log.d("Location Provider", "Location provider not available!");
		} else {
			Log.d("Location Provider", "Location provider available!");
		}
			
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, TWO_MINUTES, TEN_METERS, this);
		
		//setup();
	}
	@Override
	protected void onPause() {
		/*saveFood();*/
		super.onPause();
		/*MyLocation myLocation = new MyLocation();
		myLocation.cancelTimer();*/
	}
	@Override
	protected void onDestroy(){
		super.onDestroy();
		locationManager.removeUpdates(this);
	}
	// Stop receiving location updates whenever the Activity becomes invisible.
    @Override
    protected void onStop() {
        super.onStop();
    }
   /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
		getSupportMenuInflater().inflate(R.menu.new_food_menu, menu);
		
        return super.onCreateOptionsMenu(menu);
	}
    @Override
	public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
	    switch(item.getItemId()){
		    case R.id.SaveNewFood:
		    	
		    	return true;
		    case R.id.NewFoodLocation:
		    	
		    	return true;
		    default:
		        return false;
	    }
		
    }*/
    
	@Override
	public void onLocationChanged(Location locat) {
		lat = locat.getLatitude();
		log = locat.getLongitude();
		loc = locat;
		Log.d("Location", String.valueOf(lat) + ", " + String.valueOf(log));
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	class GetTypeFood extends AsyncTask<Void, Void, Void>{

		List<TypeFood> loai_mon_an = new ArrayList<TypeFood>() ;
		
		@Override
		protected Void doInBackground(Void... agrs) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			JSONObject json = jsonParser.makeHttpRequest(url_get_type_foods, "POST", params);
			// Check your log cat for JSON reponse
			Log.d("Load all type foods: ", json.toString());
			
			try {
				int success = json.getInt(TAG_SUCCESS);
				if(success == 1){
					JSONArray type_foods = json.getJSONArray("type_foods");
					
					for (int i = 0; i < type_foods.length(); i++){
						JSONObject c = type_foods.getJSONObject(i);

						
						
						String id = c.getString(TAG_TYPE_ID);
						String name_type = c.getString(TAG_TYPE_FOODS);
						
						TypeFood typeFood = new TypeFood();
						typeFood.setId(id);
						typeFood.setLoai_mon_an(name_type);
						
						loai_mon_an.add(typeFood);
					}
					runOnUiThread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							ArrayAdapter<TypeFood> adapter = new ArrayAdapter<TypeFood>(getApplicationContext(), 
									android.R.layout.simple_spinner_item, loai_mon_an);
							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							spnTypeFood.setAdapter(adapter);
						}
					});
					
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		
	}
	
}
